# semantic_analyzer.py
from lexer import TT_IDENTIFIER
from my_parser import Node, SelectNode, CreateTableNode, InsertNode, DeleteNode

class SemanticAnalyzer:
    def __init__(self):
        self.catalog = {}

    def analyze(self, node):
        if isinstance(node, SelectNode):
            return self.analyze_select(node)
        elif isinstance(node, CreateTableNode):
            return self.analyze_create_table(node)
        elif isinstance(node, InsertNode):
            return self.analyze_insert(node)
        elif isinstance(node, DeleteNode):
            return self.analyze_delete(node)
        else:
            return f"Unsupported statement: {type(node)}"

    def analyze_select(self, node):
        table_name = node.table.value
        if table_name not in self.catalog:
            return f"ERROR: Table '{table_name}' does not exist"
        for field in node.fields:
            if field.type == TT_IDENTIFIER and field.value not in self.catalog[table_name]:
                return f"ERROR: Column '{field.value}' not in table '{table_name}'"
        return "OK: Valid SELECT"

    def analyze_create_table(self, node):
        name = node.table_name.value
        if name in self.catalog:
            return f"ERROR: Table '{name}' already exists"
        self.catalog[name] = [col.value for col in node.columns]
        return f"OK: Table '{name}' created with {len(node.columns)} columns"

    def analyze_insert(self, node):
        name = node.table_name.value
        if name not in self.catalog:
            return f"ERROR: Table '{name}' does not exist"
        expected = len(self.catalog[name])
        got = len(node.values)
        if expected != got:
            return f"ERROR: Insert expects {expected} values, got {got}"
        return "OK: Insert valid"

    def analyze_delete(self, node):
        name = node.table_name.value
        if name not in self.catalog:
            return f"ERROR: Table '{name}' does not exist"
        return "OK: Valid DELETE"